package com.ruoyi.loginRecord.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.loginRecord.domain.AsyncLoginRecord;
import com.ruoyi.loginRecord.domain.CommonConfigInfoVo;
import com.ruoyi.loginRecord.domain.LoginConfigTimeVo;
import com.ruoyi.loginRecord.domain.LoginRecord;
import com.ruoyi.loginRecord.mapper.LoginRecordOverrideMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class LoginRecordOverrideServiceImpl {


    @Async
    @EventListener
    public void asyncRecord(AsyncLoginRecord asyncLoginRecord) {
        Long userId = asyncLoginRecord.getUserId();
        String userName = asyncLoginRecord.getUserName();
        HttpServletRequest request = asyncLoginRecord.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = ServletUtils.getClientIP(request);
        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(ip);
        s.append(address);
        s.append(getBlock(userName));
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();

        BeanFactory beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        LoginRecordOverrideMapper overrideMapper = beanFactory.getBean(LoginRecordOverrideMapper.class);
        // 查询配置时间信息
        CommonConfigInfoVo commonConfigVo = overrideMapper.getCommonConfigInfo("login_time");
        if (commonConfigVo == null) {
            return;
        }
        LoginConfigTimeVo loginTimeVo = JsonUtils.parseObject(commonConfigVo.getInfo(), LoginConfigTimeVo.class);
        if (loginTimeVo == null) {
            return;
        }

        String startTime = loginTimeVo.getStartTime();
        String endTime = loginTimeVo.getEndTime();
        if (!StringUtils.isNotBlank(startTime) || !StringUtils.isNotBlank(endTime)) {
            return;
        }
        List<String> weekConfig = loginTimeVo.getWeekConfig();
        if (CollectionUtils.isEmpty(weekConfig)) {
            return;
        }
        // 获取当前日期是周几
        String week = DateUtils.getWeek();
        if (!StringUtils.isNotBlank(week)) {
            return;
        }
        if (!weekConfig.contains(week)) {
            return;
        }
        // 比较当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.HH_mm);
        String now = simpleDateFormat.format(new Date());
        try {
            Date nowTime = simpleDateFormat.parse(now);
            Date start = simpleDateFormat.parse(startTime);
            Date end = simpleDateFormat.parse(endTime);
            if (!DateUtils.isEffectiveDate(nowTime, start, end)) {
                String date = DateUtils.getDate();
                synchronized (this) {
                    Long firstRecord = overrideMapper.getFirstRecord(DateUtils.getDate(), userId);
                    // 封装对象
                    LoginRecord logininfor = new LoginRecord();
                    logininfor.setUserId(userId);
                    logininfor.setUserName(userName);
                    logininfor.setIpaddr(ip);
                    logininfor.setLoginLocation(address);
                    logininfor.setBrowser(browser);
                    logininfor.setOs(os);
                    logininfor.setMsg("");
                    logininfor.setTimeRule(JsonUtils.toJsonString(loginTimeVo));

                    logininfor.setMethod(asyncLoginRecord.getMethod());
                    logininfor.setOperUrl(asyncLoginRecord.getOperUrl());
                    logininfor.setOperParam(asyncLoginRecord.getOperParam());
                    logininfor.setAtTime(DateUtils.getDate());
                    if (firstRecord == null) {
                        logininfor.setParentId(0L);
                    } else {
                        logininfor.setParentId(firstRecord);
                    }
                    overrideMapper.insertLoginRecord(logininfor);
                }
            }
        } catch (Exception e) {
            log.info("异常登录报错：{}", e.getMessage());
        }
    }

    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }

}
